// 自定义分页类
var MyPagination = function() {
	
	// 配置项
	var opts = {
		num_edge_entries: 3, // 前后显示的个数
		num_display_entries: 3, // 显示数
		items_per_page: 1, // 每页显示多少条
		current_page: 0, // 开始显示的页数
		link_to: "javascript:;", // 分页的href
		prev_text: "上一页", // 上一页
		next_text: "下一页", // 下一页
		ellipse_text: "...",
		prev_show_always: true,
		next_show_always: true
	}
	
	// 加载数据
	var loadData = function(o, isFirstLoad) {
		var ajaxOpts = o.ajaxOpts, handleOpts = o.handleOpts, pageOpts = o.pageOpts;
		opts = $.extend(opts, pageOpts || {}); // 继承用户的分页设置
		var url = ajaxOpts.url;
		if(!url) {
			alert('Request url should not be null.');
			return;
		}
		var type = ajaxOpts.type;
		var dataType = ajaxOpts.dataType;
		
		var params = $.extend({start: opts.current_page, limit: opts.items_per_page}, ajaxOpts.params || {});
		
		$.ajax({
			type: type,
			cache: false,
			url: url,
			data: params,
			dataType: dataType,
			success: function(data) {
				// 第一次需要总数来进行初始化
				if(isFirstLoad) {
					initPagination(o, data);
				} else {
					handleValues(o, data);
				}
			}
		});
	}
	
	// 处理数据
	var handleValues = function(o, data) {
		var formatValues = o.handleOpts.formatValues;
		if(formatValues && (formatValues instanceof Function)) {
			formatValues(data.data);
		}
	}
	
	// 初始化分页
	var initPagination = function(o, data) {
		var num_entries = data.totalCount; // 总数
		
		$(o.renderer).pagination(num_entries, {
			num_edge_entries: opts.num_edge_entries,
			num_display_entries: opts.num_display_entries,
			items_per_page: opts.items_per_page,
			current_page: opts.current_page,
			link_to: opts.link_to,
			prev_text: opts.prev_text,
			next_text: opts.next_text,
			ellipse_text: opts.ellipse_text,
			prev_show_always: opts.prev_show_always,
			next_show_always: opts.next_show_always,
			callback: function(page_index, jq) {
				pageselectCallback(page_index, jq, o);
			}
		});
	}
	
	// 分页点击后的处理方法
	var pageselectCallback = function(page_index, jq, o) {
		o.ajaxOpts.params.start = page_index;
		loadData(o, false);
		return false;
	}
	
	return {
		init: function(o) {
			loadData(o, true);
		}
	}
}();